/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package org.atomojo.app.edit;

import org.atomojo.app.AtomApplication;
import org.atomojo.app.auth.UserGuard;
import org.atomojo.www.app.edit.ClassResourceFinder;
import org.atomojo.www.app.edit.upload.UploadApplication;
import org.restlet.Application;
import org.restlet.Context;
import org.restlet.Request;
import org.restlet.Response;
import org.restlet.Restlet;
import org.restlet.data.ChallengeScheme;
import org.restlet.routing.Filter;
import org.restlet.routing.Router;
import org.restlet.routing.Template;

/**
 *
 * @author alex
 */
public class EditApplication extends Application {

   AtomApplication atomApp;
   public EditApplication(Context context,AtomApplication atomApp) {
      super(context);
      getTunnelService().setEnabled(false);

      this.atomApp = atomApp;
      for (String name : context.getParameters().getNames()) {
         String value = context.getParameters().getFirstValue(name);
         getLogger().info("Adding host parameter "+name+" -> "+value);
         context.getParameters().set(name,value,false);
      }
   }
   
   public Restlet createRoot() {
      Router router = new Router(getContext());
      router.setDefaultMatchingMode(Template.MODE_STARTS_WITH);
      router.attach("/",new ClassResourceFinder(getContext(),EditApplication.class.getClassLoader(),EditApplication.class));
      router.attach("/editor/",new ClassResourceFinder(getContext(),ClassResourceFinder.class.getClassLoader(),ClassResourceFinder.class));
      Filter uploadFilter = new Filter(getContext()) {
         protected int beforeHandle(Request request,Response response)
         {
            request.getAttributes().put("app.url", "riap://application/app/");
            return Filter.CONTINUE;
         }
      };
      uploadFilter.setNext(new UploadApplication(getContext(),atomApp));
      router.attach("/upload",uploadFilter);
      router.attach("/app",atomApp);
      Filter guard = new UserGuard(getContext(),ChallengeScheme.HTTP_BASIC,"Atom User",atomApp.getAuthService());
      guard.setNext(router);
      return guard;
   }
}
